package org.millioncall.yueyoga.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * action的监听统计拦截器
 * 
 * @author zangjinyu
 * @since 1.0.0
 * @version 1.0.0
 * 
 */
public class ActionHandlerIntercetor extends HandlerInterceptorAdapter {
	private static final Logger LOGGER = LoggerFactory
			.getLogger("mvc.action.stat.info");

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute("action_startTime", startTime);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		long endTime = System.currentTimeMillis();
		long startTime = (Long) request.getAttribute("action_startTime");
		request.removeAttribute("action_startTime");
		long processing = endTime - startTime;// action处理时间
		String requestUrl = (String) request
				.getAttribute("org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping");

		LOGGER.info("请求:" + handler.getClass().getName() + ":" + requestUrl
				+ ", 执行时间:" + processing + " ms");

		if (request.getAttribute("javax.servlet.error.exception") != null) {
			request.setAttribute(GlobalConstants.ERROR_EXCEPTION_CONTENT_KEY,
					GlobalConstants.ERROR_EXCEPTION_CONTENT_KEY);
			clearRequestExceptionAttr(request, response);
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (ex != null) {
			request.setAttribute(GlobalConstants.ERROR_EXCEPTION_CONTENT_KEY,
					ex);
		}
	}

	private void clearRequestExceptionAttr(HttpServletRequest request,
			HttpServletResponse response) {
		request.removeAttribute("javax.servlet.error.status_code");
		request.removeAttribute("javax.servlet.error.exception_type");
		request.removeAttribute("javax.servlet.error.message");
		request.removeAttribute("javax.servlet.error.exception");
		request.removeAttribute("javax.servlet.error.request_uri");
		request.removeAttribute("javax.servlet.error.servlet_name");
		response.setStatus(HttpServletResponse.SC_OK);
	}
}
